package com.example.service.impl;

import com.example.pojo.*;
import com.example.mapper.UsersMapper;
import com.example.service.IUsersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.xml.crypto.Data;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Comparator;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2024-06-01
 */
@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements IUsersService {

    @Resource
    private UsersMapper usersMapper;
    @Resource
    private RedisTemplate<String, List<Users>> redisTemplate;

    @Override
    public List<Users> getAllUsers() {
        // 首先尝试从 Redis 缓存中获取数据
        String cacheKey = "allUser";
        List<Users> cachedUser = redisTemplate.opsForValue().get(cacheKey);

        if (cachedUser == null) {
            // 如果缓存中没有数据，则从数据库中获取数据
            List<Users> userFromDB = usersMapper.getAllUsers(); // 从数据库中获取用户信息

            if (userFromDB != null) {
                // 将从数据库中获取的数据存入 Redis 缓存
                redisTemplate.opsForValue().set(cacheKey, userFromDB, Duration.ofMinutes(60)); // 设置缓存时间为60分钟
                return userFromDB;
            } else {
                // 数据库中没有找到对应用户，返回 null 或者进行其他处理
                return null;
            }
        } else {
            // 如果缓存中有数据，直接返回缓存数据
            return cachedUser;
        }
    }

    @Override
    public List<Users> getFindUsers(String select,String input) {
        return usersMapper.getFindUsers(select, input);
    }

    @Override
    public void StatusChange(int status, int uid) {
        usersMapper.StatusChange(status,uid);
    }

    @Override
    public Users Login(String name, String password) {
        // 从数据库中获取用户信息（假设此处调用的是 usersMapper 的方法）
        Users user = usersMapper.findByName(name);

        if (user != null) {
            // 获取数据库中存储的加密密码
            String hashedPasswordFromDB = user.getPassword();

            // 使用 BCrypt 校验输入的未加密密码和数据库中的加密密码是否匹配
            if (BCrypt.checkpw(password, hashedPasswordFromDB)) {
                // 密码匹配，返回用户信息
                return user;
            }
        }

        // 如果用户不存在或密码不匹配，返回 null 或者适合的错误处理
        return null;
    }

    @Override
    public void Register(String name, String phone, String password) {
        String image = "images/tx1.png";
        String gender ="male";
        //获取当前时间
        LocalDateTime now = LocalDateTime.now();
        //格式转化
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String rdata = now.format(formatter);
// 加密密码
        String hashedPassword = BCrypt.hashpw(password, BCrypt.gensalt());
        usersMapper.Register(name,phone,hashedPassword,image,gender,rdata);
    }

    @Override
    public void More(int uid) {
        usersMapper.Register2(uid);
    }

    public boolean checkPassword(String inputPassword, String hashedPassword) {
        return BCrypt.checkpw(inputPassword, hashedPassword);
    }

    @Override
    public Users findByName_pwd(String name, String password) {
        // 从数据库中获取用户信息（假设此处调用的是 usersMapper 的方法

        return usersMapper.findByName_pwd(name,password);
    }


    @Override
    public Users findByUid(Integer uid) {
        return usersMapper.findByUid(uid);
    }

    @Override
    public List<Users> findApply(Integer bid) {
        return usersMapper.findApply(bid);
    }

    @Override
    public List<Posts> findInformation(Integer uid) {
        return usersMapper.findInformation(uid);
    }

    @Override
    public List<Users> findAttention(Integer uid) {
        return usersMapper.findAttention(uid);
    }

    @Override
    public boolean gz(Integer uid, Integer otherid) {
        return usersMapper.gz(uid,otherid);
    }

    @Override
    public boolean addGz(Integer uid, Integer otherid) {
        return usersMapper.addGz(uid,otherid);
    }

    @Override
    public boolean delGz(Integer uid, Integer otherid) {
        return usersMapper.delGz(uid,otherid);
    }

    @Override
    public boolean gzbar(Integer uid, Integer bid) {
        return usersMapper.gzbar(uid,bid);
    }

    @Override
    public boolean addGzbar(Integer uid, Integer bid) {
        return usersMapper.addGzbar(uid,bid);
    }

    @Override
    public boolean delGzbar(Integer uid, Integer bid) {
        return usersMapper.delGzbar(uid,bid);
    }

    @Override
    public void updateUser(Integer uid, String name, String phone, String password, String image, String gender, Integer age, String ipaddress) {
        // 加密密码
        String hashedPassword = BCrypt.hashpw(password, BCrypt.gensalt());
        usersMapper.updateUser(uid,name,phone,hashedPassword,image,gender);
        usersMapper.updateUser2(uid,age,ipaddress);
    }

    @Override
    public boolean updateUser_image(Integer uid, String image) {
        return usersMapper.updateUser_image(uid,image);
    }

    @Override
    public String Like(Integer uid, Integer pid, Integer likes, Integer shares, Integer coins,Integer otherid) {
        if (usersMapper.findLikes(uid,pid) == null){
            usersMapper.addLikes(uid,pid);
        }
        Likes li = usersMapper.findLikes(uid,pid);

        if (li.getLikes()==0 && likes == 1){
            usersMapper.Likes(uid,pid,likes,shares,coins);
            if (coins != 0){
                usersMapper.coinsUid(uid,coins);
                usersMapper.coinsUid2(otherid,coins);
            }
            return "ok";
        }else if (li.getLikes()!=0 && likes ==1){
            return "ac";
        }
        if (li.getShares()==0 && shares ==1){
            usersMapper.Likes(uid,pid,likes,shares,coins);
            if (coins != 0){
                usersMapper.coinsUid(uid,coins);
                usersMapper.coinsUid2(otherid,coins);
            }
            return "ok";
        }else if (li.getShares()!=0 && shares ==1){
            return "fc";
        }
        if (li.getCoins()<=1 &&coins ==1){
            usersMapper.Likes(uid,pid,likes,shares,coins);
            if (coins != 0){
                usersMapper.coinsUid(uid,coins);
                usersMapper.coinsUid2(otherid,coins);
            }
            return "ok";
        }else if (li.getCoins()>1 && coins ==1){
            return "bc";
        }else {
            return "err";
        }
    }

    @Override
    public List<Bulletins> findText(Integer uid) {
        return usersMapper.findText(uid);
    }

    @Override
    public void addText(Integer uid, String content) {
        usersMapper.addText(uid,content);
    }

    @Override
    public Users userDetails(Integer uid) {
        return usersMapper.userDetails(uid);
    }

    @Override
    public void addApply(Integer uid, Integer bid) {
            if (usersMapper.findApply(uid,bid) == null){
                usersMapper.addApply(uid,bid);
            }
    }


}
